package com.feature50.clarity.formui.jfd;

import com.feature50.clarity.FormException;
import com.feature50.clarity.ResourceLoader;
import com.feature50.clarity.formui.FormUILoader;
import com.feature50.clarity.formui.FormUI;
import com.jformdesigner.model.FormModel;
import com.jformdesigner.runtime.FormLoader;
import com.jformdesigner.runtime.FormCreator;

import java.io.InputStream;

import org.apache.log4j.Logger;

public class JFormDesignerFormUILoader implements FormUILoader {
    public FormUI loadFormUI(String key) throws FormException {
        InputStream in = ResourceLoader.getInstance().getInputStream(ResourceLoader.Type.Form, key, "jfd");
        if (in == null) return null;

        try {
            FormModel formModel = FormLoader.load(in, ResourceLoader.getInstance().getClassLoader());
            FormCreator creator = new FormCreator(formModel, ResourceLoader.getInstance().getClassLoader());
            creator.setSetComponentNames(true);
            return new FormUIJFormDesigner(creator);
        } catch (Exception e) {
            throw new FormException(String.format("Couldn't load form '%1$s' with JFormDesigner", key), e);
        }
    }
}
